package org.report4service.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.report4service.model.Report;

/**
 * Serializes objects from bytes and vice versa
 *
 * @author Jonathan
 */
public class Serializer {

    private ReportParser parser = new ReportParser();

    public Serializer() {
    }

    public byte[] serialise(String data) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);

        dos.writeUTF(data);
        dos.flush();

        dos.close();
        baos.close();

        return baos.toByteArray();
    }

    public Report deserialise(byte[] data, int recordId, int maxRecords) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        DataInputStream dis = new DataInputStream(bais);
        Report report = parser.getReport(dis.readUTF(), recordId, maxRecords);
        bais.reset();
        dis.close();
        bais.close();
        return report;
    }

    public String deserialise(byte[] data) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        DataInputStream dis = new DataInputStream(bais);
        String value = dis.readUTF();
        bais.reset();
        dis.close();
        bais.close();
        return value;
    }
}
